<template>
  <div class="search-suggestion">
    <van-cell icon="location-o" v-for="(suggestion, i) in suggestions" :key="i" @click="$emit('search',suggestion)" >
        <template slot="title">
            <div v-html="highlight(suggestion)"></div>
        </template>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search.js'
import { debounce} from  'lodash'
export default {
  name: 'searchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      suggestions: [],
    }
  },
  methods: {
    async loadSearchSuggestion(q) {
      try {
        const { data: res } = await getSearchSuggestions(q)
        this.suggestions = res.data.options
      } catch (err) {
        this.$toast('获取搜索建议失败')
      }
    },
    highlight(suggestion){
        let highlightStr = `<span style="color:red;">${this.searchText}</span>`
        
        const reg = new RegExp(this.searchText,'gi');

        return suggestion.replace(reg,highlightStr)
    }
  },
  created() {},
  watch: {
    searchText: {
    //   handler(value) {
    //     // console.log(value)
    //     this.loadSearchSuggestion(value)
    //   },
      handler:debounce(function(value){
          this.loadSearchSuggestion(value)
      },300),
      immediate: true,
    },
  },
}
</script>

<style lang="" scoped>
</style>